import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
//=================
//image page:http://ragecomics.com/c/9w93/not-a-rage
//imageURL:http://ragecomics.com/-img/503838751861334b48000f62.png?w=600&h=664
//image page:http://ragecomics.com/c/9w8z/every-bloody-time
//imageURL:http://ragecomics.com/-img/503836ea1861334b48000f58.png?w=600&h=901
//image page:http://ragecomics.com/c/9w8y/tales-of-injuries-part-1
//imageURL:http://ragecomics.com/-img/503836ea1861334b48000f56.png?w=600&h=443
//image page:http://ragecomics.com/c/9w99/have-sex-with-a-cactus-already-did-that
//imageURL:http://ragecomics.com/-img/503839471861334b48000f6e.png?w=600&h=664
//page:http://ragecomics.com/new?a=ysdam&p=12
public class MainRagecomicsCom {
	public static final String STARTPAGE = "http://ragecomics.com/new?b=yuduy&p=12";
	public static final String DOMAIN = "http://ragecomics.com";

	public static String toURL(String url) {
		if (url.toLowerCase().startsWith("http://")) {
			return url;
		} else {
			return DOMAIN + url;
		}
	}

	public static String saveTo = null;
	static {
		saveTo = "E:\\Android\\暴走漫画系列\\autodownload\\RagecomicsCom\\"
				+ new Date().getTime() + "\\";
		File f = new File(saveTo);
		if (!f.exists()) {
			f.mkdirs();
		}
	}
	public static int imageCounter = 1;

	public static void main(String[] args) throws IOException {
		Document doc = Jsoup.parse(new URL(STARTPAGE), 1000 * 120);
		while (true) {
			Elements imagePageElements = doc.select("h4 a");
			eachPageHandler(imagePageElements);
			Element nextPageLink = doc.select("li.next a").first();
			String nextPageUrl = toURL(nextPageLink.attr("href"));
			System.out.println("page:" + nextPageUrl);
			System.out.println("=================");
			URL nextPageURL = new URL(nextPageUrl);
			doc = Jsoup.parse(nextPageURL, 1000 * 120);
		}
	}

	private static void eachPageHandler(Elements imagePageElements) {
		for (int i = 0; i < imagePageElements.size(); i++) {
			try {
				Element eachElement = imagePageElements.get(i);
				String eachURL = toURL(eachElement.attr("href"));
				System.out.println("image page:" + eachURL);
				Document doc = Jsoup.parse(new URL(eachURL), 1000 * 120);
				Element imageElement = doc.select("div[class=main comic] img")
						.first();
				String imageURL = toURL(imageElement.attr("src"));
				System.out.println("imageURL:" + imageURL);
				String title = doc.select("h1").first().text();
				downloadImage(imageURL, title);
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			} 
		}
	}

	static String getExtensionByContentType(String contentType) {
		if (contentType == null) {
			return "";
		}
		return contentType.substring(contentType.lastIndexOf("/") + 1,
				contentType.length());
	}

	private static void downloadImage(String urlString, String imageName)
			throws IOException {
		String imageFileName = toFileName(imageName);
		// 构造URL
		URL url = new URL(urlString);
		// 打开连接
		URLConnection con = url.openConnection();
		String contentType = con.getContentType();
		con.setConnectTimeout(1000 * 60);
		con.setReadTimeout(1000 * 60);
		// 输入流
		InputStream is = con.getInputStream();
		// 1K的数据缓冲
		byte[] bs = new byte[1024];
		// 读取到的数据长度
		int len;
		// 输出的文件流
		OutputStream os = new FileOutputStream(saveTo + imageFileName + "."
				+ getExtensionByContentType(contentType));
		// 开始读取
		while ((len = is.read(bs)) != -1) {
			os.write(bs, 0, len);
		}
		// 完毕，关闭所有链接
		os.close();
		is.close();
	}

	private static String toFileName(String imageName) {
		if (imageName == null || imageName.trim().equals("")) {
			return String.valueOf(System.currentTimeMillis());
		}
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < imageName.length(); i++) {
			char c = imageName.charAt(i);
			if (!Character.isDigit(c) && !Character.isLetter(c)) {
				sb.append("_");
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}
}
